<template>
  <div :style="{ width: width ? `${width}px` : '100%' }">
    <el-upload
      ref="uploadRef"
      :file-list="fileList"
      class="upload-demo"
      :headers="headers"
      :action="action"
      multiple
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :before-remove="beforeRemove"
      :limit="limit"
      :accept="accept"
      :list-type="listType"
      :on-exceed="handleExceed"
      :before-upload="beforeUpload"
    >
      <div
        class="upload-normal-button"
        v-if="
          !listType &&
          (limitShowButton || (!limitShowButton && fileList.length < limit))
        "
      >
        <el-button type="primary" plain v-if="isPlain">
          <svg-icon name="upload" size="14px" />
          {{ uploadText }}</el-button
        >
        <el-button type="primary" v-else> {{ uploadText }}</el-button>
        <span class="tip">{{ tip }}</span>
      </div>
      <div
        class="upload-picture-button"
        v-if="listType === 'picture-card' && fileList.length < limit"
      >
        <el-icon><Plus /></el-icon>
        <span>{{ uploadText }}</span>
      </div>
    </el-upload>
    <el-dialog v-model="dialogVisible" class="previw-dialog">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, watch, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'
import { genFileId } from 'element-plus'
const props = defineProps({
  // 双向绑定的文件数据
  modelValue: { type: Array, default: () => [] },
  // 文件上传数量限制
  limit: {
    type: Number,
    default: 1000,
  },
  fileSize: {
    type: Number,
  },
  // 满足上传数量后是否显示上传按钮
  limitShowButton: {
    type: Boolean,
    default: true,
  },
  // 上传组件类型：默认普通类型，picture-card 为图片类型
  listType: {
    type: String,
  },
  // 上传按钮文字内容
  uploadText: {
    type: String,
    default: '点击上传文件',
  },
  // 允许上传文件类型
  accept: {
    type: String,
  },
  // 上传提示
  tip: {
    type: String,
  },
  // 上传组件宽度
  width: {
    type: [Number, String],
  },
  // 上传按钮样式：是否线框型
  isPlain: {
    type: Boolean,
    default: false,
  },
})
const uploadRef = ref()
const fileList = ref([])
const userStore = useUserStore()
const action =
  (process.env.NODE_ENV === 'production' ? window.BASE_URL : '/api') +
  '/resource/file/upload/file'
const headers = computed(() => {
  return {
    Auth_token: userStore.token,
  }
})
watch(
  () => props.modelValue,
  () => {
    if (props.modelValue.length !== fileList.value.length) {
      let tempFlie = []
      props.modelValue.forEach((file) => {
        tempFlie.push({
          name: file.fileName,
          status: 'success',
          uid: file.pkid,
          pkid: file.pkid,
          url: file.fileUrl,
          response: {
            data: file.pkid,
            message: null,
            success: true,
          },
        })
      })
      fileList.value = tempFlie
    }
  },
  {
    immediate: true,
    deep: true,
  },
)
const emit = defineEmits(['update:modelValue'])
watch(
  () => fileList,
  () => {
    let files = []
    fileList.value.forEach((item) => {
      files.push({
        fileName: item.name,
        fileUrl: item.url,
        pkid: item.response.data,
      })
    })
    emit('update:modelValue', files)
  },
  {
    deep: true,
  },
)
const handleSuccess = (res, file, files) => {
  fileList.value = files
}
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const handlePreview = (uploadFile) => {
  if (props.listType === 'picture-car') {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
  }
}
const handleRemove = () => {}
const beforeRemove = () => {}
const handleExceed = (files) => {
  ElMessage.warning('最多上传' + props.limit + '个文件')
}
const beforeUpload = (file) => {
  const fileSize = file.size / 1024 / 1024
  const isOverflow = props.fileSize && fileSize > props.fileSize
  if (isOverflow) {
    ElMessage.warning(`文件大小不能超过${props.fileSize}M`)
  }
  return !isOverflow
}
</script>
<style lang="scss" scoped>
:deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
  background: transparent;
  border: none;
}
:deep(.el-upload-list--picture-card) {
  .el-upload-list__item {
    width: 120px;
    height: 120px;
  }
}
:deep(.el-upload--text) {
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
}
:deep(.el-upload-list--text) {
  width: 100%;
  margin-top: 0;
}
:deep(.previw-dialog) {
  width: auto;
  background: transparent;
  .el-dialog__header {
    border-bottom: none;
  }
  .el-dialog__body {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .el-dialog__close {
    color: #ffffff;
  }
}
.upload-normal-button {
  display: flex;
  align-items: flex-end;
  justify-content: flex-start;
  .tip {
    color: #b4b7bc;
    font-size: 12px;
    line-height: 12px;
    margin: 0 0 5px 5px;
  }
}
.upload-picture-button {
  width: 120px;
  height: 120px;
  background: rgba(153, 155, 157, 0.05);
  border: 1px dashed #d5deed;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .avatar {
    width: 100%;
    height: 100%;
    border-radius: 4px;
  }
  .el-icon {
    font-size: 70px;
    color: #d5deed;
  }
  span {
    font-size: 14px;
    font-weight: 400;
    color: #d5deed;
  }
}
</style>
